package com.company.cloud.coupon.modules.mgr.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import com.company.cloud.common.bean.BaseClientResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.LocalDateTimeUtils;
import com.company.cloud.coupon.modules.app.service.CouponService;
import com.company.cloud.coupon.modules.base.entity.CouponConfigInfo;
import com.company.cloud.coupon.modules.base.entity.CouponInfo;
import com.company.cloud.coupon.modules.base.service.CouponConfigInfoService;
import com.company.cloud.coupon.modules.base.service.CouponInfoService;
import com.company.cloud.coupon.modules.cache.models.CouponModel;
import com.company.cloud.coupon.modules.cache.utils.CouponChangeUtils;
import com.company.cloud.coupon.modules.mgr.controller.req.CouponQuery4PageParam;
import com.company.cloud.coupon.modules.mgr.controller.req.CouponSendParam;
import com.company.cloud.coupon.modules.mgr.controller.req.CouponStateUpdateParam;
import com.company.cloud.coupon.modules.mgr.controller.req.CouponUseParam;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 优惠券管理
 */
@Authc
@RestController
@RequestMapping("/mgr/op/coupon")
@Api(tags = "OP_Mgr_优惠券管理")
public class CouponInfoMgrController {

	@Autowired
	private CouponConfigInfoService couponConfigInfoService;
	@Autowired
	private CouponInfoService couponInfoService;
	@Autowired
	private CouponService couponService;
	@Autowired
	private UserRemoteService userRemoteService;

	@PostMapping("/query")
	@ApiOperation(value = "查询", response = CouponModel.class)
	public BaseResult query(@RequestBody CouponQuery4PageParam params) {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		LocalDateTime haveDateGt=null;
		LocalDateTime haveDateLt=null;
		if(StringUtils.hasText(params.getHaveDateGt())) {
			haveDateGt=LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getHaveDateGt());
		}
		if(StringUtils.hasText(params.getHaveDateLt())) {
			haveDateLt=LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getHaveDateLt());
		}
		LocalDateTime usableDateGt=null;
		LocalDateTime usableDateLt=null;
		if(StringUtils.hasText(params.getUsableDateGt())) {
			usableDateGt=LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getUsableDateGt());
		}
		if(StringUtils.hasText(params.getUsableDateLt())) {
			usableDateLt=LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getUsableDateLt());
		}
		
		IPage<CouponInfo> page = couponInfoService.page(new Page<>(params.getPage(), params.getRows()),
				new QueryWrapper<CouponInfo>()
				.eq("company_no",userInfo.getCompanyNo())
				.eq(StringUtils.hasText(params.getCouponNo()), "coupon_no", params.getCouponNo())
				.eq(CheckUtils.hasInt(params.getCouponConfigId()), "coupon_config_id", params.getCouponConfigId())
				.eq(CheckUtils.hasInt(params.getHaveUserId()), "have_user_id", params.getHaveUserId())
				.eq(StringUtils.hasText(params.getState()), "state", params.getState())
				.ge(CheckUtils.hasObj(haveDateLt), "have_date", haveDateLt)
				.le(CheckUtils.hasObj(haveDateGt), "have_date", haveDateGt)
				.ge(CheckUtils.hasObj(usableDateLt), "usable_date", usableDateLt)
				.le(CheckUtils.hasObj(usableDateGt), "usable_date", usableDateGt)
				);
				
		if(page==null || CollectionUtils.isEmpty(page.getRecords())) {
			return BaseResult.ok();
		}
		Set<Integer> userIds=new HashSet<Integer>();
		page.getRecords().forEach(item->{
			userIds.add(item.getHaveUserId());
		});

		BaseClientResult<Map<Integer, UserSimple>> userResp=userRemoteService.getUserMapByIds(userIds);
		Map<Integer, UserSimple> userMap=BaseClientResult.getResultData(userResp,new HashMap<>());
		IPage<CouponModel> data = page.convert(new Function<CouponInfo, CouponModel>() {
			@Override
			public CouponModel apply(CouponInfo entity) {
				UserSimple user= userMap.get(entity.getHaveUserId());
				return CouponChangeUtils.getCoupon(entity,user);
			}
		});
		return BaseResult.ok(data);
	}

	@GetMapping("/get")
	@ApiOperation(value = "详情", response = CouponModel.class)
	public BaseResult get(@RequestParam("couponNo") String couponNo) {
		CouponInfo entity = couponInfoService.getById(couponNo);
		if (entity == null) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		BaseClientResult<UserSimple> userResp=userRemoteService.getUserById(entity.getHaveUserId());
		//todo 判断
		UserSimple user=BaseClientResult.getResultData(userResp);
		CouponConfigInfo couponConfig = couponConfigInfoService.getById(entity.getCouponConfigId());
		CouponModel model = CouponChangeUtils.getCoupon(entity,user,couponConfig);
		return BaseResult.ok(model);
	}

	@PostMapping("/send")
	@ApiOperation(value = "发送", response = BaseResult.class)
	public BaseResult send(@RequestBody CouponSendParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		couponService.sendCoupon(params, userInfo);
		return BaseResult.ok();
	}

	@PostMapping("/use")
	@ApiOperation(value = "使用", response = BaseResult.class)
	public BaseResult use(@RequestBody CouponUseParam params) {
		return BaseResult.ok();
	}

	@PostMapping("/updateState")
	@ApiOperation(value = "修改状态", response = BaseResult.class)
	public BaseResult updateState(@RequestBody CouponStateUpdateParam params) {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		CouponInfo entity = couponInfoService.getById(params.getCouponNo());
		if (entity == null) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		if (entity.getState().equals(params.getState())) {
			return BaseResult.ok();
		}
		entity.setState(params.getState());
		entity.setRemark(params.getRemark());
		entity.addEditParam(userInfo);
		couponInfoService.updateById(entity);
		return BaseResult.ok();
	}

}